const httpStatus = require('http-status');
const NutritionSuggestion = require('../models/nutritionSuggestion.model');
const ApiError = require('../utils/ApiError');
const logger = require('../config/logger');
const mongoose = require('mongoose');

/**
 * 创建营养建议
 * @param {Object} suggestionData
 * @returns {Promise<NutritionSuggestion>}
 */
const createNutritionSuggestion = async (suggestionData) => {
  logger.info('【营养建议创建】开始创建营养建议');
  logger.debug('【营养建议创建】建议内容:', JSON.stringify({
    userId: suggestionData.userId,
    type: suggestionData.type,
    content: suggestionData.content,
    relevantFoodsCount: suggestionData.relevantFoods?.length || 0
  }));

  try {
    const nutritionSuggestion = await NutritionSuggestion.create(suggestionData);
    logger.info(`【营养建议创建】创建成功, ID: ${nutritionSuggestion._id}`);
    return nutritionSuggestion;
  } catch (error) {
    logger.error('【营养建议创建】创建失败:', error);
    throw error;
  }
};

/**
 * 查询营养建议列表
 * @param {Object} filter - 查询条件
 * @param {Object} options - 分页和排序选项
 * @returns {Promise<Object>} - 包含结果和分页信息的对象
 */
const queryNutritionSuggestions = async (filter, options) => {
  logger.info('【营养建议查询】开始查询营养建议列表');
  logger.debug('【营养建议查询】查询条件:', JSON.stringify(filter));
  logger.debug('【营养建议查询】查询选项:', JSON.stringify(options));

  const { sortBy, limit = 10, page = 1 } = options;
  const skip = (page - 1) * limit;

  // 添加未删除条件
  const query = { ...filter, isDeleted: { $ne: true } };

  // 处理日期范围查询
  if (filter.startDate) {
    query.createdAt = { ...query.createdAt, $gte: new Date(filter.startDate) };
    delete query.startDate;
  }
  if (filter.endDate) {
    query.createdAt = { ...query.createdAt, $lte: new Date(new Date(filter.endDate).setHours(23, 59, 59, 999)) };
    delete query.endDate;
  }

  // 构建排序条件
  const sortOptions = {};
  if (sortBy) {
    const parts = sortBy.split(',');
    parts.forEach(part => {
      const [key, order] = part.split(':');
      sortOptions[key] = order === 'desc' ? -1 : 1;
    });
  } else {
    // 默认按创建时间倒序排序
    sortOptions.createdAt = -1;
  }

  try {
    // 输出详细的查询条件，帮助排查问题
    logger.info(`【营养建议查询】最终查询条件: ${JSON.stringify(query)}`);
    logger.info(`【营养建议查询】排序条件: ${JSON.stringify(sortOptions)}`);
    logger.info(`【营养建议查询】分页: skip=${skip}, limit=${limit}`);

    // 执行查询
    const countPromise = NutritionSuggestion.countDocuments(query);
    const suggestionsPromise = NutritionSuggestion.find(query)
      .populate([
        {
          path: 'userId',
          select: 'name avatar',
        },
        {
          path: 'relevantFoods.foodId',
          select: 'name image calories nutrition',
        },
      ])
      .sort(sortOptions)
      .skip(skip)
      .limit(limit)
      .lean();

    const [totalResults, results] = await Promise.all([countPromise, suggestionsPromise]);
    
    const totalPages = Math.ceil(totalResults / limit);
    
    logger.info(`【营养建议查询】查询成功，共找到 ${totalResults} 条记录，返回 ${results.length} 条`);
    
    // 记录查询结果的一些基本信息，帮助排查
    if (results.length === 0) {
      logger.warn('【营养建议查询】未找到任何匹配的记录，请检查查询条件或确认数据库中是否有数据');
      
      // 如果没有找到数据，尝试不带任何过滤条件查询一下，看看是否有数据
      const totalCount = await NutritionSuggestion.countDocuments({});
      logger.info(`【营养建议查询】数据库中总共有 ${totalCount} 条营养建议记录`);
      
      if (totalCount > 0) {
        // 如果存在数据，但当前查询没有匹配到，可能是过滤条件问题
        logger.info('【营养建议查询】数据库中存在记录，但当前查询条件没有匹配到，请检查过滤条件');
        
        // 检查是否是userId过滤导致
        if (filter.userId) {
          const userIdCount = await NutritionSuggestion.countDocuments({ userId: filter.userId });
          logger.info(`【营养建议查询】userId=${filter.userId} 相关的记录数: ${userIdCount}`);
        }
      }
    } else {
      logger.debug(`【营养建议查询】第一条结果: ${JSON.stringify(results[0])}`);
    }
    
    return {
      results,
      page,
      limit,
      totalPages,
      totalResults,
    };
  } catch (error) {
    logger.error('【营养建议查询】查询失败:', error);
    throw error;
  }
};

/**
 * 根据ID获取营养建议
 * @param {ObjectId} id - 营养建议ID
 * @returns {Promise<NutritionSuggestion>}
 */
const getNutritionSuggestionById = async (id) => {
  logger.info(`【营养建议查询】查询ID为 ${id} 的营养建议`);

  try {
    const suggestion = await NutritionSuggestion.findOne({
      _id: id,
      isDeleted: { $ne: true }
    }).populate([
      {
        path: 'userId',
        select: 'name avatar',
      },
      {
        path: 'relevantFoods.foodId',
        select: 'name image calories nutrition',
      },
    ]);

    if (!suggestion) {
      logger.warn(`【营养建议查询】未找到ID为 ${id} 的营养建议`);
      throw new ApiError(httpStatus.NOT_FOUND, '未找到营养建议');
    }

    logger.info(`【营养建议查询】成功查询到ID为 ${id} 的营养建议`);
    return suggestion;
  } catch (error) {
    logger.error(`【营养建议查询】查询失败:`, error);
    throw error;
  }
};

/**
 * 更新营养建议
 * @param {ObjectId} id - 营养建议ID
 * @param {Object} updateData - 更新数据
 * @returns {Promise<NutritionSuggestion>}
 */
const updateNutritionSuggestion = async (id, updateData) => {
  logger.info(`【营养建议更新】更新ID为 ${id} 的营养建议`);
  logger.debug('【营养建议更新】更新内容:', JSON.stringify(updateData));

  try {
    const suggestion = await getNutritionSuggestionById(id);
    
    Object.assign(suggestion, updateData);
    await suggestion.save();
    
    logger.info(`【营养建议更新】更新成功`);
    return suggestion;
  } catch (error) {
    logger.error(`【营养建议更新】更新失败:`, error);
    throw error;
  }
};

/**
 * 删除营养建议（逻辑删除）
 * @param {ObjectId} id - 营养建议ID
 * @returns {Promise<NutritionSuggestion>}
 */
const deleteNutritionSuggestion = async (id) => {
  logger.info(`【营养建议删除】删除ID为 ${id} 的营养建议`);

  try {
    const suggestion = await getNutritionSuggestionById(id);
    
    suggestion.isDeleted = true;
    await suggestion.save();
    
    logger.info(`【营养建议删除】删除成功`);
    return suggestion;
  } catch (error) {
    logger.error(`【营养建议删除】删除失败:`, error);
    throw error;
  }
};

/**
 * 一次性将所有用户的营养建议标记为已读
 * @param {ObjectId} userId - 用户ID
 * @returns {Promise<Object>} - 包含更新数量的结果对象
 */
const markAllSuggestionsAsRead = async (userId) => {
  logger.info(`【营养建议更新】将用户 ${userId} 的所有未读建议标记为已读`);

  try {
    const result = await NutritionSuggestion.updateMany(
      { userId, isRead: false, isDeleted: { $ne: true } },
      { isRead: true }
    );

    logger.info(`【营养建议更新】共标记了 ${result.modifiedCount} 条建议为已读`);
    return { modifiedCount: result.modifiedCount };
  } catch (error) {
    logger.error(`【营养建议更新】标记已读失败:`, error);
    throw error;
  }
};

module.exports = {
  createNutritionSuggestion,
  queryNutritionSuggestions,
  getNutritionSuggestionById,
  updateNutritionSuggestion,
  deleteNutritionSuggestion,
  markAllSuggestionsAsRead,
};